package com.atguigu.controller;

import com.atguigu.model.system.SysUser;
import com.atguigu.result.Result;
import com.atguigu.security.custom.LoginUserInfoHelper;
import com.atguigu.service.SysUserService;
import com.atguigu.utils.MD5;
import com.atguigu.vo.system.SysUserQueryVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin/system/sysUser")
@Api(tags = "用户管理")
@CrossOrigin
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @PreAuthorize("hasAuthority('bnt.sysUser.list')")
    @GetMapping("/{page}/{limit}")
    @ApiOperation("分页查询")
    public Result<IPage> getPage(@PathVariable Integer page, @PathVariable Integer limit, SysUserQueryVo sysUserQueryVo){
        IPage<SysUser> page1=new Page<>(page,limit);
        IPage<SysUser> pageList = sysUserService.getPageList(page1, sysUserQueryVo);
        return Result.ok(pageList);
    }
    @PreAuthorize("hasAuthority('bnt.sysUser.add')")
    @PostMapping("save")
    @ApiOperation("新增用户")
    public Result save(@RequestBody SysUser sysUser){
        String password = sysUser.getPassword();
        String encrypt = MD5.encrypt(password);
        sysUser.setPassword(encrypt);
        sysUserService.saveUser(sysUser);
        return Result.ok();
    }
    @PreAuthorize("hasAuthority('bnt.sysUser.list')")
    @GetMapping("get/{id}")
    @ApiOperation("根据id获取角色")
    public Result getById(@PathVariable Integer id){
        SysUser sysUser=sysUserService.getUserById(id);
        return Result.ok(sysUser);
    }
    @PreAuthorize("hasAuthority('bnt.sysUser.update')")
    @PutMapping("update")
    @ApiOperation("修改角色")
    public Result update(@RequestBody SysUser sysUser){
        sysUserService.updateUser(sysUser);
        return Result.ok();
    }
    @PreAuthorize("hasAuthority('bnt.sysUser.remove')")
    @DeleteMapping("/delete/{id}")
    @ApiOperation("根据id删除角色")
    public Result deleteById(@PathVariable Integer id){
        sysUserService.removeById(id);
        return Result.ok();
    }
    @PreAuthorize("hasAuthority('bnt.sysUser.update')")
    @PutMapping("updateStatus")
    @ApiOperation("修改角色状态")
    public Result updateStatus(@RequestBody SysUser sysUser){
        sysUserService.updateStatus(sysUser);
        return Result.ok();
    }
    @GetMapping("getCurrentUser")
    public Result getCurrentUser(){
        Long userId = LoginUserInfoHelper.getUserId();
        SysUser sysUser = sysUserService.getUserById(userId.intValue());
        return Result.ok(sysUser);
    }
}
